package com.a2.appa3.ui.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.google.gson.Gson;
import com.nanchen.compresshelper.CompressHelper;
import com.a2.appa3.R;
import com.a2.appa3.adapter.z_palnFragmentAdapter;
import com.a2.appa3.global.HttpAdress;
import com.a2.appa3.global.Info;
import com.a2.appa3.model.CustomObserver;
import com.a2.appa3.model.network.HttpJsonUtils;
import com.a2.appa3.model.network.entity.req.Emojicon;
import com.a2.appa3.model.network.entity.req.Faceicon;
import com.a2.appa3.model.network.entity.req.WebSocketMsgBeannew;
import com.a2.appa3.model.network.entity.req.uploadPicBean;
import com.a2.appa3.model.network.entity.req.uploadPicBena;
import com.a2.appa3.util.BaseLoadingDialog;
import com.a2.appa3.util.DisplayRules;
import com.a2.appa3.util.EventBus.changechatlist;
import com.a2.appa3.util.OnEndLessScrollListener;
import com.a2.appa3.util.SYSOUtils;
import com.a2.appa3.util.WebSocketUtils2;
import com.a2.appa3.widget.KJChatKeyboard;
import com.a2.appa3.widget.OnOperationListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.shihao.library.XStatusBarHelper;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class ChatActivity1 extends BaseActivitySimple {
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.headerTitle)
    TextView headerTitle;
    @BindView(R.id.headerButton)
    ImageView headerButton;
    private RecyclerView recyclewviewlist;
    private SwipeRefreshLayout mlist_srf;
    private z_palnFragmentAdapter adapter;
    private boolean ismovetoposition = false;//默认是滚动的
    private MyLinnerlayout manager;
    private RelativeLayout right1;  //滚动
    private RelativeLayout right2;  //清楚
    private RelativeLayout right4;  //头像
    private ImageView right1img;
    private ImageView pic_guidepage_3;
    private TextView right1text;
    private KJChatKeyboard box;
    public static String DIRECTORY_DCIM = "DCIM";
    public static int REQUEST_CODE = 666;
    private boolean qun = false;
    private int upload = 0;
    //    private int page;
    private String Refreshid;
    private String Refreshtype;
    private String Refreshuuid;
    private boolean autobottom = true;//新消息是否自动置底
    private OnEndLessScrollListener onEndLessScrollListener;

    @Override
    protected void onResume() {
        super.onResume();
        adapter.notifyDataSetChanged();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        try {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (Build.VERSION.SDK_INT >= 21) {
            //解决Android5.0以上，状态栏设置颜色后变灰的问题
            XStatusBarHelper.tintStatusBar(this, getResources().getColor(R.color.settingbg));
        }
//新消息是否自动置底
        autobottom = true;

        String name = getIntent().getStringExtra("chatname");
        String type = getIntent().getStringExtra("chattype");
        String id = getIntent().getStringExtra("chatid");
        SYSOUtils.sOut_("聊天室获取" + name + type + id);
        Refreshid = id;
        Refreshtype = type;
        if (!TextUtils.isEmpty(name)) {
            headerTitle.setText(name);
        } else {
            headerTitle.setText("聊天");
        }
        if (name.equals("万盛聊天室")) {
            qun = true;
        }
        if (!TextUtils.isEmpty(type) && type.equals("room")) {
            //群聊显示右上角群管理按钮
            headerButton.setVisibility(View.VISIBLE);
            headerButton.setImageResource(R.mipmap.groupmeneager);
        } else {
            headerButton.setVisibility(View.INVISIBLE);
        }
        /**
         * 跳转群管理
         */
        headerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ChatActivity1.this, GroupManageActivity.class);
                intent.putExtra("roomid", id + "");
                startActivity(intent);
            }
        });
        gethistorychat(id, type, "LT", "");


        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        InitView();
        initEvents();
        box.setOnOperationListener(new OnOperationListener() {
            @Override
            public void send(String content) {
                changelayout();
                if (!content.isEmpty()) {
                    try {
                        //先加密韦url  再base64加密
                        String text1 = URLEncoder.encode(content, "utf-8");
                        String encodeWord = Base64.encodeToString(text1.getBytes("utf-8"), Base64.DEFAULT);
                        WebSocketUtils2.getInstance().sendMsg(encodeWord);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void selectedFace(Faceicon content) {
            }

            @Override
            public void selectedEmoji(Emojicon emoji) {
                changelayout();
                box.getEditTextBox().append(emoji.getValue());
                SYSOUtils.sOut_("点击表情++++++++++++++++++++++++++++++++++++++++++++++日志");
            }

            @Override
            public void selectedBackSpace(Emojicon back) {
                DisplayRules.backspace(box.getEditTextBox());
            }

            @Override
            public void selectedFunction(int index) {
                changelayout();
                switch (index) {
                    case 0:
                        Intent intent = new Intent("android.intent.action.GET_CONTENT");
                        intent.setType("image/*");
                        startActivityForResult(intent, 999);//打开系统相册
                        upload = 999;//这是发送图片
                        break;
                    case 1:
                        SYSOUtils.sOut_("相机++++++++++++++++++++++++++++++++++++++++++++++日志");
                        Intent pIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//调用摄像头action
                        startActivityForResult(pIntent, 666);//requestcode
                        upload = 666;//相机回调code
                        break;
                }
            }

            @Override
            public void edchangelayout() {
                SYSOUtils.sOut_("方法响应++++++++++++++++++++++++++++++++++++++++++++++日志");
            }
        });


        //表情
        List<String> faceCagegory = new ArrayList<>();
        File faceList = new File("");
        if (faceList.isDirectory()) {
            File[] faceFolderArray = faceList.listFiles();
            for (File folder : faceFolderArray) {
                if (!folder.isHidden()) {
                    faceCagegory.add(folder.getAbsolutePath());
                }
            }
        }
        box.setFaceData(faceCagegory);
        recyclewviewlist.setOnTouchListener(getOnTouchListener());

//        } catch (Exception e) {
//        }
    }

    private void gethistorychat(String id, String type, String w, String index) {
        HttpJsonUtils.getHttpApiInstance()
                .getList(HttpAdress.getuseAdress() + "api/chatapi/ChatLog/getList", Info.Token, id, index, w, type, "")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<WebSocketMsgBeannew>() {
                    @Override
                    protected void onCustomNext(WebSocketMsgBeannew bean) {
                        mlist_srf.setRefreshing(false);
                        SYSOUtils.sOut_("添加之前的长度" + Info.mdatas.size());
                        if (bean.code == 0 && bean.data.size() != 0) {
                            Refreshuuid = bean.data.get(0).uuid;
                            for (int i = 0; i < bean.data.size(); i++) {
                                try {
                                    String string = new String(Base64.decode((((String) bean.data.get(i).msg)).getBytes(), Base64.DEFAULT));
                                    String text2 = java.net.URLDecoder.decode(string, "utf-8");
                                    SYSOUtils.sOut_("hhuoqu获取到的是" + text2);
                                    if (text2.contains("img=")) {
                                        if (bean.data.get(i).status == 2) {
                                            bean.data.get(i).status = 22;
                                        }
                                        if (bean.data.get(i).status == 4) {
                                            bean.data.get(i).status = 44;
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                Info.mdatas.add(bean.data.get(i));
                            }
                            SYSOUtils.sOut_("添加之后的长度" + Info.mdatas.size());
                            if (Info.mdatas.size() > 2) {
                                MoveToPosition(manager, recyclewviewlist, Info.mdatas.size() - 1);
                            }
                            adapter.notifyDataSetChanged();
                        } else {
                            Toast.makeText(ChatActivity1.this, "没有更多记录了哦", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {
                        mlist_srf.setRefreshing(false);
                    }
                });


    }

    private void changelayout() {
        if (Info.mdatas.size() > 2) {
            MoveToPosition(manager, recyclewviewlist, Info.mdatas.size() - 1);
        }
        adapter.notifyDataSetChanged();
    }

    private void initEvents() {
        //锁屏
        right1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ismovetoposition = !ismovetoposition;
                if (ismovetoposition) {
                    right1img.setImageResource(R.mipmap.chat_ungundong);
                    right1text.setText("锁屏");
                } else {
                    right1img.setImageResource(R.mipmap.chat_gundong);
                    right1text.setText("滚屏");
                }
            }
        });
        //清屏
        right2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Info.mdatas.clear();
                adapter.notifyDataSetChanged();
            }
        });
//        //修改昵称
//        right3.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //修改昵称
////                Intent intent = new Intent(this, changeNikeDiolog.class);
////                startActivity(intent);
//            }
//        });
        //修改头像
        right4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("android.intent.action.GET_CONTENT");
                intent.setType("image/*");
                startActivityForResult(intent, 999);//打开系统相册
                upload = 888;//这是修改头像
            }
        });


    }

    @SuppressLint("WrongViewCast")
    private void InitView() {
        box = (KJChatKeyboard) findViewById(R.id.chat_msg_input_box);
        recyclewviewlist = findViewById(R.id.mlist);
        right1 = findViewById(R.id.right1);
        right2 = findViewById(R.id.right2);
        mlist_srf = findViewById(R.id.mlist_srf);
//        right3 = findViewById(R.id.right3);
        right4 = findViewById(R.id.right4);
        right1img = findViewById(R.id.right1img);
        right1text = findViewById(R.id.right1text);
        pic_guidepage_3 = findViewById(R.id.pic_guidepage_3);


//        page = 0;
        mlist_srf.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light);

        mlist_srf.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                SYSOUtils.sOut_("XIA下拉并关闭自动置底部++++++++++++++++++++++++++++++++++++++++++++++++");
                autobottom = false;
                gethistorychat(Refreshid, Refreshtype, "LT", Refreshuuid);
            }
        });
        manager = new MyLinnerlayout(this);
        onEndLessScrollListener = new OnEndLessScrollListener(manager) {
            @Override
            public void getMoreData(int currentPage) {
                autobottom = true;
                SYSOUtils.sOut_("shangla上拉+++++++++++++++++++++++++");
//                gethistorychat(id, type, "LT", "");
            }
        };


        recyclewviewlist.setLayoutManager(manager);
        //添加滑动监听
        recyclewviewlist.addOnScrollListener(onEndLessScrollListener);


        adapter = new z_palnFragmentAdapter(this, Info.mdatas, qun);
        recyclewviewlist.setAdapter(adapter);
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_chat1;

    }


    //解决notifyinsert的bug
    public class MyLinnerlayout extends LinearLayoutManager {
        public MyLinnerlayout(Context context) {
            super(context);
        }

        @Override
        public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
            try {
                super.onLayoutChildren(recycler, state);
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 若软键盘或表情键盘弹起，点击上端空白处应该隐藏输入法键盘
     *
     * @return 会隐藏输入法键盘的触摸事件监听器
     */
    private View.OnTouchListener getOnTouchListener() {
        return new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                box.hideLayout();
                box.hideKeyboard(ChatActivity1.this);
                return false;
            }
        };
    }

    /**
     * RecyclerView 移动到当前位置，
     */
    public static void MoveToPosition(LinearLayoutManager manager, RecyclerView mRecyclerView, int n) {
        int firstItem = manager.findFirstVisibleItemPosition();
        int lastItem = manager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            mRecyclerView.scrollToPosition(n);
        } else if (n <= lastItem) {
            int top = mRecyclerView.getChildAt(n - firstItem).getTop();
            mRecyclerView.scrollBy(0, top);
        } else {
            mRecyclerView.scrollToPosition(n);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清空聊天室信息
        Info.mdatas.clear();
        try {
            String str = "";
            final JSONObject result = new JSONObject();
            result.put("controller", "Action");
            result.put("action", "exitWindow");
            String text1 = URLEncoder.encode(result.toString(), "utf-8");
            String encodeWord = null;
            encodeWord = Base64.encodeToString(text1.getBytes("utf-8"), Base64.DEFAULT);
            str = "type=ins&message=" + encodeWord;
            WebSocketUtils2.getInstance().sendMsg(str);
        } catch (Exception e) {
            e.printStackTrace();
        }

        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Eventrefresh(changechatlist messageEvent) {
        SYSOUtils.sOut_("接收到新的消息的长度" + Info.mdatas.size());
        if (Info.mdatas.size() > 2 && autobottom) {
            MoveToPosition(manager, recyclewviewlist, Info.mdatas.size() - 1);
        }
        adapter.notifyDataSetChanged();
//        if (messageEvent.type.equals("refresh")) {
        // 震动 1s
//        }
    }

    //发送图片
    //选择图片的回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 999 && resultCode == this.RESULT_OK && null != data) {
            if (Build.VERSION.SDK_INT >= 19) {
                handleImageOnKitkat(data);
            }
        } else if (requestCode == REQUEST_CODE) {
            if (Build.VERSION.SDK_INT >= 19) {
                Bundle pBundle = data.getExtras(); //从intent对象中获取数据，
                if (pBundle != null) {
                    Bitmap pBitmap = (Bitmap) pBundle.get("data");
                    if (pBitmap != null) {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        pBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                        byte[] bytes = baos.toByteArray();
                        Glide.with(this)
                                .load(bytes)
                                .into(new GlideDrawableImageViewTarget(pic_guidepage_3) {
                                          @Override
                                          public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
                                              super.onResourceReady(drawable, anim);
                                              scaleAndPush(drawable);
                                          }
                                      }
                                );
                    }
                }
            }
        }
    }

    private void scaleAndPush(GlideDrawable drawable) {
        pic_guidepage_3.setDrawingCacheEnabled(true);
        OutputStream os = null;
        try {
            dialog = new BaseLoadingDialog(this, R.style.custom_dialog2);
            dialog.show();
            File file = new File(getFilesDir() + "/logo.png");
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            Bitmap bitmap = drawableToBitmap(drawable.getCurrent());
            SYSOUtils.sOut_("+++++++++++++++++++" + bitmap.toString());
            os = new FileOutputStream(file);
            SYSOUtils.sOut_("相机图片正常daxiao" + file.length());
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
            os.flush();
            os.close();
            SYSOUtils.sOut_("相机图片压缩后大小" + file.length());
            String strbm = fileToBase64(String.valueOf(file));
            post_requst_paly(strbm);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            pic_guidepage_3.setDrawingCacheEnabled(false);
        }
    }

    @TargetApi(19)
    private void handleImageOnKitkat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            //如果是document类型的uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content:" +
                        "//downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果是content类型的uri，则使用普通方式处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            //如果是File类型的uri，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        SYSOUtils.sOut_("++++++++++++++++++++++++++++++++++++++" + imagePath.toString());
        displayImage(imagePath);//根据图片路径显示图片
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过uri和selection来获取真实的图片路径
        Cursor cursor = this.getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    Gson gson = new Gson();
    private BaseLoadingDialog dialog;

    //首先压缩图片
    public void displayImage(String path) {
        dialog = new BaseLoadingDialog(this, R.style.custom_dialog2);
        dialog.show();
//        //开始上传
        File file = new File(path);
        SYSOUtils.sOut_("压缩前相ce图片正常大小" + file.length());
        File newFile = CompressHelper.getDefault(this).compressToFile(file);
        SYSOUtils.sOut_("压缩后相ce图片正常大小" + newFile.length());
        String strbm = fileToBase64(String.valueOf(newFile));
//            //相册
        post_requst_paly(strbm);
    }

    //开始上传图片
    public void post_requst_paly(String strs) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
        uploadPicBean bean = new uploadPicBean();
        bean.picture = "data:image/png;base64," + strs;
        bean.token = Info.user.token;
        String json = gson.toJson(bean);
        Log.e("xdh", "开始上传图片");
        long starttime = System.currentTimeMillis();
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
                , json);
        final Request request = new Request.Builder()
                .url(HttpAdress.getuseAdress() + "api/mobile/upimgtxt")//请求的url
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                dialog.dismiss();
                SYSOUtils.sOut_("上传失败，原因是" + e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                uploadPicBena bena1 = gson.fromJson(response.body().string(), uploadPicBena.class);
                long stoptime = System.currentTimeMillis();
                Log.e("xdh", "上传图片成功" + (stoptime - starttime) + bena1.toString());
                if (bena1.isStatus()) {
                    SYSOUtils.sOut_("上传成功，地址是" + bena1.getUrl());
                    //上传图片成功，需要再发普通消息，将我们的Url广播出去
                    String text1 = java.net.URLEncoder.encode("img=" + bena1.getUrl() + "&data=", "utf-8");
                    String encodeWord = Base64.encodeToString(text1.getBytes("utf-8"), Base64.NO_WRAP);
                    WebSocketUtils2.getInstance().sendMsg(encodeWord);
                }
                dialog.dismiss();
            }
        });
    }

    ////////////////////////////////////////////////////////////////////////////////
    public static Bitmap drawableToBitmap(Drawable drawable) {
        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();

//        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }

    public static String fileToBase64(String path) {
        String base64 = null;
        InputStream in = null;
        try {
            File file = new File(path);
            in = new FileInputStream(file);
            byte[] bytes = new byte[(int) file.length()];
            in.read(bytes);
            base64 = Base64.encodeToString(bytes, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return base64;
    }
}
